package com.example.pan.ui.setting

import android.os.Bundle
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.example.pan.R
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect


@AndroidEntryPoint
class SettingsFragment : PreferenceFragmentCompat() {

    private val mViewModel: SettingsViewModel by viewModels()

    @ExperimentalCoroutinesApi
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.preference_setting)
        lifecycleScope.launchWhenCreated {
            mViewModel.settingsData.collect {
                findPreference<Preference>("dir")?.apply {
                    summary = it.globalOption.dir
                }
                findPreference<ListPreference>("theme_mode")?.apply {
                    value = it.themeMode.toString()
                    setOnPreferenceChangeListener { _, newValue ->
                        mViewModel.setThemeMode(newValue.toString().toInt())
                        true
                    }
                }
            }
        }
    }

}